package com.kmxd.ams.core.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kmxd.ams.core.common.constant.CacheConst;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 系统参数缓存工具类
 *
 * @author admin
 */
public class ConfigUtil {

  public static String getCacheKey(String key) {
    return CacheConst.CACHE_PREFIX_SYS_CONFIG + ":" + key;
  }

  public static String getConfigValue(String key) {
    if (StrUtil.isBlank(key)) {
      return "";
    }
    Object obj = SpringUtil.getBean(RedisUtils.class).get(getCacheKey(key));
    return Objects.nonNull(obj) ? obj.toString() : "";
  }

  public static void setConfigCache(String key, String value) {
    if (StrUtil.isBlank(key) || StrUtil.isBlank(value)) {
      return;
    }
    SpringUtil.getBean(RedisUtils.class).set(getCacheKey(key), value);
  }

  public static void clearConfigCache() {
    Collection<String> keys = SpringUtil.getBean(RedisUtils.class).keys(getCacheKey("*"));
    SpringUtil.getBean(RedisUtils.class).del(keys.toArray(new String[0]));
  }

  /**
   * 根据key获取指定指
   *
   * @param content
   * @param key
   * @return
   */
  public static String getVal(String content, String key) {
    if (StrUtil.isBlank(content) || !JSONUtil.isTypeJSON(content)) {
      return null;
    }
    JSONObject fileType = JSONUtils.parseObj(content);
    return fileType.getStr(key, "");
  }

  /**
   * 根据key对象获取list
   *
   * @param content
   * @param key
   * @return
   */
  public static List<String> getStrs(String content, String key) {
    return StrUtil.split(getVal(content, key), ",");
  }
}
